<template>
	<el-dialog title="树洞-AI助手" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="true" :fullscreen="true"
		:destroy-on-close="true" class="cyber-healing-chat">
		<div class="chat-history">
			<div v-for="(message, index) in chatHistory" :key="index"
				:class="[message.role === 'user' ? 'user-message' : 'ai-message']">
				<div class="message-bubble">
					<span class="message-content">{{ message.content }}</span>
				</div>
			</div>
		</div>
		<div class="input-container">
			<el-input type="text" v-model="newMessage" placeholder="别闷闷不乐了，来分享点美好事物吧，让心灵充满阳光！" class="message-input"
				:disabled="isSending" @keyup.enter.native="sendMessage">
				<template #append>
					<el-button icon="el-icon-send" :loading="isSending" @click="sendMessage">
						{{ isSending ? '发送中...' : '发送' }}
					</el-button>
				</template>
			</el-input>
		</div>
	</el-dialog>
</template>

<script>
	import axios from 'axios';
	import {
		debounce
	} from "@/utils/common.js";
	import {
		postChatMessage
	} from '@/api/chat'; // 引入封装的 API 函数
	import {
		getInfo
	} from "@/api/dict";
	export default {
		data() {
			return {
				newMessage: '',
				chatHistory: [], // 聊天历史记录
				dialogVisible: false, // 弹窗显示状态
				isSending: false,
				apiKey: "", //ai key
				api_model: "", //ai 模型名称 如 deepseek-ai/DeepSeek-V3
				//deepseek-ai/DeepSeek-R1-Distill-Llama-8B

			};
		},
		mounted() {
			this.handledInitKey()
		},
		methods: {
			handledInitKey() {
				let obj = {
					code: 'ai_apiKey'
				};

				getInfo(obj).then(res => {
					try {
						if (res.data && res.data.length > 0) {
							this.apiKey = res.data[0].value
						}
					} catch (err) {
						if (!this.apiKey) {
							this.$message.error("未配置Key--无法使用");
						} else {
							this.$message.error(err.message);
						}
					}
				});
				getInfo({
					code: 'ai_model'
				}).then(res => {
					try {
						if (res.data && res.data.length > 0) {
							this.api_model = res.data[0].value
						}
					} catch (err) {
						if (!this.api_model) {
							this.$message.error("未配置模型--无法使用");
						} else {
							this.$message.error(err.message);
						}
					}
				});

			},
			handledInit(flag = true) {
				this.dialogVisible = flag
			},
			sendMessage: debounce(async function() {
				if (!this.apiKey) {
					this.$message.error("未配置Key--无法使用");
					return
				}
				if (!this.api_model) {
					this.$message.error("未配置模型--无法使用");
					return
				}
				const vm = this; // 保存 Vue 实例的上下文

				// 将用户消息添加到聊天历史记录中
				const userMessage = {
					role: 'user',
					content: this.newMessage,
					id: new Date().getTime().toString()
				};
				vm.chatHistory.push(userMessage);

				// 设置当前请求的 ID

				const options = {
					method: 'POST',
					headers: {
						"accept": "application/json",
						Authorization: 'Bearer ' + this.apiKey,
						'Content-Type': 'application/json'
					},
					stream: true,
					body: JSON.stringify({
						model: this.api_model,
						messages: [{
							role: "user",
							content: this.newMessage
						}],
						stream: true,
						max_tokens: 4096,
						stop: ["null"],
						temperature: 0.7,
						top_p: 0.7,
						top_k: 50,
						frequency_penalty: 0.5,
						n: 1,
						response_format: {
							type: "text"
						},
						// tools: [{
						// 	type: "function",
						// 	function: {
						// 		description: "<string>",
						// 		name: "<string>",
						// 		parameters: {},
						// 		strict: false
						// 	}
						// }]
					})
				};
				const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', options);
				if (!response.ok) {
					vm.$message.error(response.statusText)
					throw new Error(`HTTP error! status: ${response.status}`);
				}

				const reader = response.body.getReader();
				const decoder = new TextDecoder();
				let responseData = {}; // 存储完整的响应数据

				function chunkLoop() {
					reader.read().then(async ({
						done,
						value
					}) => {
						if (done) {
							console.log('Stream completed');
							return;
						}

						const chunk = decoder.decode(value, {
							stream: true
						});
						processChunk(chunk);
						await chunkLoop();
					}).catch(err => {
						console.error('Error reading stream:', err);
					});
				}

				function processChunk(chunk) {
					const lines = chunk.split('\n');
					lines.forEach(line => {
						line = line.trim();
						if (line.startsWith('data: ')) {
							const data = line.substring(6);
							if (data === '[DONE]') return;
							handleData(data);
						}
					});
				}

				function handleData(data) {
					try {
						const json = JSON.parse(data);
						if (json.choices && json.choices.length > 0) {
							const delta = json.choices[0].delta;
							const id = json.id;
							const aiMessage = vm.chatHistory.find(item => item.id === id && item.role ===
								'assistant');

							if (aiMessage) {
								// 逐步追加内容
								if (delta.content != null) {
									aiMessage.content += delta.content;
								}
							} else {
								// 新的 id，创建新的消息
								const newAiMessage = {
									role: 'assistant',
									content: delta.content,
									id: id
								};
								vm.chatHistory.push(newAiMessage);
							}
						}
					} catch (error) {
						console.error('Error parsing JSON:', error);
					}
				}

				chunkLoop();
				vm.newMessage = '';
			}),
		},
	};
</script>

<style scoped>
	.cyber-healing-chat {
		/* 赛博治愈风格背景 */
		--el-dialog-background: #f0f4ff;
		--el-dialog-border: 1px solid #e0e7ff;
		--el-dialog-header: #ffffff;
		--el-dialog-header-font-color: #404040;
		margin-top: 0;
	}

	.cyber-healing-chat :deep(.el-dialog) {
		margin-top: 0;
		background-image: linear-gradient(to top, #bdc2e8 0%, #bdc2e8 1%, #e6dee9 100%);
		border-radius: 8px;
	}

	.chat-history {
		min-height: 200px;
		height: 60vh;
		overflow-y: auto;
		padding: 20px;
		background: #ffffff;
		border-radius: 10px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
		margin-bottom: 20px;
	}

	.message-bubble {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		padding: 10px;
		border-radius: 10px;
		max-width: 90%;
		word-wrap: break-word;
	}

	.user-message {
		background: #e0f7fa;
		/* 浅蓝色背景 */
		color: #000000;
		/* 黑色文字 */
		align-self: flex-end;
		/* 用户消息右对齐 */
	}

	.ai-message {
		background: #fff3e0;
		/* 浅黄色背景 */
		color: #000000;
		/* 黑色文字 */
		align-self: flex-start;
		/* AI 消息左对齐 */
	}

	.message-content {
		font-size: 14px;
		font-family: Arial, sans-serif;
		line-height: 1.5;
		white-space: pre-wrap;
		/* 允许自动换行 */
	}

	.input-container {
		display: flex;
		align-items: center;
		background: #ffffff;
		border-radius: 10px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	.message-input {
		flex: 1;
		padding: 10px;
		border: none;
		outline: none;
		font-size: 14px;
		font-family: Arial, sans-serif;
	}

	.message-input::placeholder {
		color: #a0a0a0;
	}

	.el-button {
		flex: 1;
		background: #409EFF;
		/* Element UI 主题色 */
		color: #ffffff;
		border: none;
		border-radius: 5px;
		font-size: 14px;
		cursor: pointer;
	}

	.el-button:hover {
		background: #66b1ff;
	}

	/* 添加输入框禁用时的样式 */
	.message-input.is-disabled .el-input__inner {
		background-color: #f5f7fa;
		border-color: #e4e7ed;
		color: #c0c4cc;
		cursor: not-allowed;
	}

	/* 添加发送按钮禁用时的样式 */
	.el-button.is-disabled {
		background-color: #a0cfff;
		color: #ffffff;
		cursor: not-allowed;
	}

	/* 加载中的样式 */
	.el-button.is-loading {
		background-color: #66b1ff;
	}
</style>